package santiago.domain;

import java.util.HashMap;
import java.util.Map;
import santiago.exception.InvalidAmountException;

public class BribeSession {

    private int PlayerNbr;
    private Map<Player, Bribe> Bribes;

    public BribeSession(int PlayerNbr) {
        this.PlayerNbr = PlayerNbr;
        Bribes = new HashMap<>();
    }

    public void addBribe(Player Player, Player SupportedPlayer, int Amount, Canal Canal) throws InvalidAmountException {
        if (Player.getCash() < Amount) {
            throw new InvalidAmountException();
        }
        if (Player == SupportedPlayer) {
            Bribes.put(Player, new Bribe(Player, Amount, Canal));
        } else {
            Bribe Bribe = Bribes.get(SupportedPlayer);
            Bribe.addSupportPlayer(Player, Amount);
        }
    }

    public Bribe getBribe(Player Player) {
        Bribe[] Bribes = getBribes();
        for (int i = 0; i < Bribes.length; i++) {
            if (Bribes[i].getSupportedPlayer() == Player) {
                return Bribes[i];
            }
        }
        return null;
    }

    public Bribe[] getBribes() {
        return Bribes.values().toArray(new Bribe[Bribes.values().size()]);
    }

    public boolean hasFinished() {
        return getPlayerCount() == PlayerNbr - 1;
    }

    private int getPlayerCount() {
        int PlayerCount = 0;
        for (Map.Entry<Player, Bribe> entry : Bribes.entrySet()) {
            PlayerCount += entry.getValue().getPlayerCount();
        }
        return PlayerCount;
    }
}
